<template>
  <div id="app">
    <button class="btn" id="create" @click="createNote">创建便签</button>
    <el-popconfirm title="确认清除所有便签？" @confirm="removeAll()">
      <button class="btn" id="remove" slot="reference">清除所有便签</button>
    </el-popconfirm>
    <button class="btn" id="login" v-if="!isLogin" @click="loginVisible = true">登录</button>
    <button class="btn" id="logout" v-if="isLogin" @click="logout">注销</button>

    <VueDragResize
      contentClass="m-note"
      dragCancel=".u-edit"
      v-for="(item,index) in notes"
      :key="index"
      :isActive="false"
      :w=item.width
      :h=item.height
      :x=item.left
      :y=item.top
      :z=item.z
      :parentW="parentW"
      :parentH="parentH"
      :parentLimitation="true"
      :isResizable="item.isResizable"
      v-on:resizestop="resizestop"
      @activated="onActivated(item)"
      @deactivated="deactivated(item)"
      v-on:dragstop="dragstop($event, item)"
    >
      <el-popconfirm title="确认删除此便签？" @confirm="del(item)">
        <i class="u-close" slot="reference"></i>
      </el-popconfirm>
      <div class="u-bar"></div>
      <textarea class="u-edit" placeholder="请输入内容" v-model="item.content" v-on:keyup="textChange(item)"></textarea>
      <!-- <el-input
        class="u-edit"
        type="textarea"
        placeholder="请输入内容"
        v-model="item.content">
      </el-input> -->
      <!-- <div class="u-edit" contenteditable="true" >{{item.content}}</div> -->
      <div class="m-time"><span class="u-timestamp">{{item.time}}</span></div>
    </VueDragResize>

    <el-dialog
      title="登录注册"
      :visible.sync="loginVisible"
      :center=true
      width="30%">
      <el-form ref="loginForm" :model="loginForm" label-width="80px">
        <el-form-item label="邮箱地址">
          <el-input v-model="loginForm.email"></el-input>
        </el-form-item>
        <el-form-item label="你的密码">
          <el-input v-model="loginForm.password" type="password"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="loginVisible = false">取 消</el-button>
        <el-button @click="singup">注册</el-button>
        <el-button type="primary" @click="login">登录</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import VueDragResize from "vue-drag-resize";
import uuid from "./utils/uuid"
import debounce from "./utils/debounce"
import timeFormat from "./utils/timeFormat"
export default {
  name: "App",
  components: {
    VueDragResize,
  },
  data() {
    return {
      parentW:1920,
      parentH:800,
      defaultNote: {width:320,height:320,left:100,top:50,content:'',time:timeFormat(new Date(),'yyyy年mm月dd日 hh时MM分'),isActive:false,isResizable:true,z:'auto'},
      notes:[],
      isLogin:false,
      loginVisible:false,
      userUID:null,
      addForm:{},
      editForm:{},
      newPosition:{},
      loginForm:{
        email: null,
        password: null,        
      }
    };
  },
  created() {
    // let user = JSON.parse(window.sessionStorage.getItem("user"));
    // this.userUID = user.uid;
    // console.log('this.$cloudbase.auth().currentUser', this.$cloudbase.auth().currentUser.uid);
    this.userUID =  this.$cloudbase.auth().currentUser?.uid;
    if(this.userUID){
      this.isLogin = true
    }
    this.handleGetNotes();
  },
   mounted() {
    // const that = this;
    this.parentW = Number( `${document.documentElement.clientWidth}` );
    this.parentH = Number( `${document.documentElement.clientHeight}` );
    window.onresize = () => {
        this.parentW = Number( `${document.documentElement.clientWidth}` );
        this.parentH = Number( `${document.documentElement.clientHeight}` );
    }
  },
  methods: {
    resizestop(newRect) {
      console.log('newRect',newRect)
    },
    dragstop($event, item){
      this.newPosition = $event;
      // console.log('$event',$event)
      // console.log('item',item);
      // console.log('item.left',item.left);
      // console.log('$event.left',$event.left);
      // console.log('move left',Math.abs(item.left - $event.left));
      // console.log('move top',Math.abs(item.top - $event.top));
      if(Math.abs(item.left - $event.left)<50 && Math.abs(item.top - $event.top)<50){return}
      this.editForm = Object.assign({userUID:this.userUID},item,this.newPosition);
      this.$cloudbase.callFunction({
        name:"updatePosition",
        data:this.editForm
      }).then(res=>{
        console.log('更新 位置',res); 
      }).catch(err=>{
        console.log('err',err);
      });  
    },
    createNote(){
      if(!this.isLogin){
        this.$message({
          message: '请登录后操作',
          type: 'warning'
        });
        return
      }
      this.addForm = Object.assign({userUID:this.userUID,uuid:uuid()},this.defaultNote,this.newPosition);
      console.log('this.addForm',this.addForm);
      this.$cloudbase.callFunction({
        name:"addNote",
        data:this.addForm
      }).then(res=>{
        this.handleGetNotes();
        console.log('createNote res',res); 
      }).catch(err=>{
        console.log('err',err);
      });
      
    },
    handleGetNotes(){
      if(!this.isLogin){
        this.$message({
          message: '请登录后操作',
          type: 'warning'
        });
        return
      }
      this.$cloudbase.callFunction({
        name:'getNotes',
        data:{userUID:this.userUID}
      }).then(res=>{
         console.log('handleGetNotes res',res);
        this.notes = res.result.data;
        // console.log('this.bookmarks',this.bookmarks);
      }).catch(err=>{
        console.log('err',err);
      })
    },
    del(item){
      console.log(item)
      this.$cloudbase.callFunction({
        name:'delNotes',
        data:{userUID:this.userUID,id:item._id}
      }).then(res=>{
        this.handleGetNotes();
         console.log('del res',res);
        // console.log('this.bookmarks',this.bookmarks);
      }).catch(err=>{
        console.log('err',err);
      })

    },
    removeAll(){
      if(!this.isLogin){
        this.$message({
          message: '请登录后操作',
          type: 'warning'
        });
        return
      }
      this.$cloudbase.callFunction({
        name:'removeAllNotes',
        data:{userUID:this.userUID}
      }).then(res=>{
        this.handleGetNotes();
         console.log('removeAll res',res);
        // console.log('this.bookmarks',this.bookmarks);
      }).catch(err=>{
        console.log('err',err);
      })
    },
    login() {
      const app = this.$cloudbase;
      app
        .auth()
        .signInWithEmailAndPassword(
          this.loginForm.email,
          this.loginForm.password
        )
        .then((res) => {
          this.loginVisible = false;
          this.isLogin = true;
          let user = {uid:res.user.uid,nickName:res.user.nickName};
          // console.log('user',user);          
          this.userUID = res.user.uid;
          this.handleGetNotes();
          console.log('login res',res);          
        window.sessionStorage.setItem("user", JSON.stringify(user));

        }).catch(err=>{
          this.alert.alertMsg = err.message;
          this.alert.showAlert = this.alert.dismissSecs;
          // console.log('err',err);
        });
      console.log("登录");
    },
    singup() {
      console.log("注册");
      const app = this.$cloudbase;
      app
        .auth()
        .signUpWithEmailAndPassword(
          this.loginForm.email,
          this.loginForm.password
        )
        .then((res) => {
          console.log("注册 res", res);
          this.$message({
            message: '申请成功，请前往邮箱验证！',
            type: 'success'
          });
          // 发送验证邮件成功
        })
        .catch((err) => {
          this.toast.msg = err;
          this.$bvToast.show("toast");
          // console.log("注册 err", this.toast.msg);
        });
    },
    logout(){
      window.sessionStorage.clear();
      this.isLogin = false;
    },
    textChange(item){
      let that = this;
      console.log('item',item)
      this.editForm = Object.assign({userUID:this.userUID},item,this.newPosition);
      this.editForm.time = timeFormat(new Date(),'yyyy年mm月dd日 hh时MM分');
      console.log('this.editForm',this.editForm);
      let handleUpdate = function(){
        that.$cloudbase.callFunction({
          name:"updateNote",
          data:that.editForm
        }).then(res=>{
          console.log('更新 res',res); 
        }).catch(err=>{
          console.log('err',err);
        });
      };
      debounce(
       handleUpdate,1000
      )
    },
    onActivated(item){
      item.z=999
    },
    deactivated(item){
      item.z='auto'
    }
  },
};
</script>

<style>
@import url("./style.css");
</style>
